<template>
  <el-dialog :title="dialogData.title"
             :visible.sync="visible"
             center
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="80%">
    <el-form :model="formdata"
             label-position="right"
             ref="formdRefs"
             label-width="120px"
             :rules="formRules">
      <el-form-item label="服务名称："
                    prop="name">
        <el-input v-model="formdata.name"
                  maxlength="50"
                  autocomplete="off"
                  style="width:50%"
                  clearable
                  placeholder="请输入服务名称"></el-input>
      </el-form-item>
      <el-form-item label="标签：">
        <el-input v-model="formdata.label"
                  maxlength="50"
                  autocomplete="off"
                  style="width:50%"
                  clearable
                  placeholder="请输入标签"></el-input>
      </el-form-item>
      <el-form-item label="列表图片："
                    prop="imageUrl">
        <el-upload class="avatar-uploader"
                   :action="imageUploadUrl"
                   :show-file-list="false"
                   accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="formdata.imageUrl"
               :src="formdata.imageUrl"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情图片："
                    prop="detailImageUrl">
        <el-upload multiple
                   :limit='6'
                   :action="imageUploadUrl"
                   accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                   list-type="picture-card"
                   :on-success="handlePictureCardPreview"
                   :file-list='formdata.detailImage'
                   :on-exceed='onexceed'
                   :on-remove='onremove'
                   :before-upload="beforeAvatarUpload">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="服务选项："
                    prop="itemList">
        <el-button type="success"
                   @click="handleAdd(0)">新 增 一 项</el-button>
        <el-table :data="formdata.itemList"
                  class="mt-20"
                  border>
          <el-table-column prop="price"
                           label="价格（元）"
                           width="240">
            <template slot-scope="scoped">
              <el-form-item :rules="serviceRules.price"
                            :prop="`itemList.${scoped.$index}.price`">
                <el-input-number :min="0"
                                 :precision="2"
                                 :controls="false"
                                 v-model="scoped.row.price"
                                 type="number"
                                 class="w-200"
                                 placeholder="请输入价格"></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="content"
                           label="描述">
            <template slot-scope="scoped">
              <el-form-item :rules="serviceRules.content"
                            :prop="`itemList.${scoped.$index}.content`">
                <el-input v-model.number="scoped.row.content"
                          show-word-limit
                          type="textarea"
                          maxlength="500"
                          placeholder="请输入描述"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="goodsItemId"
                           label="关联商品"
                           width="240">
            <template slot-scope="scoped">
              <el-form-item :rules="serviceRules.goodsItemId"
                            :prop="`itemList.${scoped.$index}.goodsItemId`">
                <el-select v-model="scoped.row.goodsItemId"
                           clearable
                           placeholder="请选择关联商品"
                           class="w-200">
                  <el-option v-for="it in getAllGoodsItem"
                             :key="it.id"
                             :label="it.name"
                             :value="it.id"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="tips"
                           label="温馨提示"
                           width="240">
            <template slot-scope="scoped">
              <el-form-item :rules="serviceRules.tips"
                            :prop="`itemList.${scoped.$index}.tips`">
                <el-input v-model="scoped.row.tips"
                          clearable
                          class="w-200"
                          placeholder="请输入温馨提示"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="address"
                           label="操作"
                           width="100">
            <template slot-scope="scoped">
              <el-button type="danger"
                         @click='delTable(scoped.$index,formdata.itemList)'>删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="标配服务："
                    prop="standardService">
        <el-input v-model="formdata.standardService"
                  maxlength="500"
                  show-word-limit
                  type="textarea"
                  :rows="4"
                  autocomplete="off"
                  clearable
                  placeholder="请输入标配服务"
                  style="width:50%"></el-input>
      </el-form-item>
      <el-form-item label="特色亮点："
                    prop="featuredHighlights">
        <el-input v-model="formdata.featuredHighlights"
                  maxlength="500"
                  show-word-limit
                  type="textarea"
                  :rows="4"
                  clearable
                  autocomplete="off"
                  placeholder="请输入特色亮点"
                  style="width:50%"></el-input>
      </el-form-item>

      <el-form-item label="医学知识："
                    prop="loreList">
        <el-button type="success"
                   @click="handleAdd(1)">新 增 一 项</el-button>
        <el-table :data="formdata.loreList"
                  class="mt-20"
                  border>
          <el-table-column prop="name"
                           label="项目名称">
            <template slot-scope="scoped">
              <el-form-item :rules="loreListRules.name"
                            :prop="`loreList.${scoped.$index}.name`">
                <el-input v-model="scoped.row.name"
                          maxlength="50"
                          clearable
                          placeholder="请输入项目名称"
                          autocomplete="off"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="clinicalWorth"
                           label="临床意义">
            <template slot-scope="scoped">
              <el-input type="textarea"
                        :rows="4"
                        show-word-limit
                        v-model="scoped.row.clinicalWorth"
                        clearable
                        placeholder="请输入临床意义"
                        maxlength="500"
                        autocomplete="off"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="address"
                           label="图片"
                           width="120">
            <template slot-scope="scoped">
              <el-upload class="avatar-uploader"
                         :action="imageUploadUrl"
                         :show-file-list="false"
                         accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                         :on-success="(response, file, fileList) =>loreListSuccess(response, file, fileList, scoped.$index)"
                         :before-upload="beforeAvatarUpload">
                <img v-if="scoped.row.imageUrl"
                     :src="scoped.row.imageUrl"
                     class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop="address"
                           label="操作"
                           width="100">
            <template slot-scope="scoped">
              <el-button type="danger"
                         @click='delTable(scoped.$index, formdata.loreList)'>删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="医学知识链接："
                    prop="loreListOther">
        <el-button type="success"
                   @click="handleAdd(2)">新 增 一 项</el-button>
        <el-table :data="loreListOther"
                  class="mt-20"
                  border>
          <el-table-column prop="name"
                           label="链接标题">
            <template slot-scope="scoped">
              <el-input v-model="scoped.row.name"
                        maxlength="50"
                        clearable
                        placeholder="请输入链接标题"
                        autocomplete="off"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="linkUrl"
                           label="链接">
            <template slot-scope="scoped">
              <el-input type="textarea"
                        :rows="4"
                        show-word-limit
                        v-model="scoped.row.linkUrl"
                        maxlength="500"
                        placeholder="请输入链接"
                        autocomplete="off"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           width="100">
            <template slot-scope="scoped">
              <el-button type="danger"
                         @click='delTable(scoped.$index,loreListOther)'>删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="医生服务："
                    prop="doctorServiceList">
        <el-button type="success"
                   @click="handleAdd(3)">新 增 一 项</el-button>
        <el-table :data="formdata.doctorServiceList"
                  class="mt-20"
                  border>
          <el-table-column prop="name"
                           label="服务名称">
            <template slot-scope="scoped">
              <el-input v-model.number="scoped.row.name"
                        clearable
                        placeholder="请输入服务名称"
                        maxlength="50"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="content"
                           label="服务释义">
            <template slot-scope="scoped">
              <el-input type="textarea"
                        :rows="4"
                        show-word-limit
                        v-model.number="scoped.row.content"
                        clearable
                        placeholder="请输入服务释义"
                        maxlength="500"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="option"
                           label="操作"
                           width="100">
            <template slot-scope="scoped">
              <el-button type="danger"
                         @click="delTable(scoped.$index,formdata.doctorServiceList)">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="推广分成：">
        <el-input-number :min="0"
                         :precision="2"
                         :controls="false"
                         v-model="formdata.extendFee"
                         type="number"
                         placeholder="请输入"
                         style="width:50%"></el-input-number>
      </el-form-item>
      <el-form-item label="购买服务后，是否填写健康服务号："
                    label-width="240px">
        <el-radio-group v-model="formdata.isInvitationCode">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <p align="center">
      <el-button @click="modalClose">取 消</el-button>
      <el-button type="primary"
                 @click="onSubmit">保 存</el-button>
    </p>
  </el-dialog>
</template>

<script>
  export default {
    props: ['dialogData', 'visible'],
    data () {
      return {
        getAllGoodsItem: [],
        formRules: {
          name: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
          imageUrl: [{ required: true, message: '请填上传列表图片', trigger: 'blur' }],
          detailImageUrl: [{ required: true, message: '请上传详情图片', trigger: ['blur', 'change'] }],
          itemList: [{ required: true, message: '请完善服务选项', trigger: 'blur' }],
          standardService: [{ required: true, message: '请输入标配服务', trigger: 'blur' }],
          featuredHighlights: [{ required: true, message: '请输入特色亮点', trigger: 'blur' }],
          doctorServiceList: [{ required: true, message: '请配置医生服务', trigger: 'blur' }],
          loreList: [{ required: true, message: '请配置医学知识', trigger: 'blur' }],
        },
        serviceRules: {
          price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
          content: [{ required: false, message: '请输入描述', trigger: 'blur' }],
          goodsItemId: [{ required: true, message: '请选择关联商品', trigger: 'change' }],
          tips: [{ required: false, message: '请输入温馨提示', trigger: 'blur' }],
        },
        loreListRules: {
          name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        },
        formdata: {
          type: 2,
          imageUrl: null,
          detailImageUrl: [],
          detailImage: [],
          itemList: [],
          isInvitationCode: 0,
          loreList: [], // 医学知识
          extendFee: '',
          doctorServiceList: [], // 医生服务
        },
        detailImageUrlArr: [],
        loreListOther: [{
          type: 2
        }],
        imageUploadUrl: this.api.appUpgradeUpload.url,
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      handleAdd (index) {
        switch (index) {
          case 0: // 服务选项
            this.formdata.itemList.push({
              price: '',
              content: '',
              goodsItemId: '', // 关联商品
              tips: '', // 温馨提示
            });
            break
          case 3:
            this.formdata.doctorServiceList.push({
              name: '',
              content: '',
            });
            break
          case 1:
            this.formdata.loreList.push({
              type: 1,
              name: '',
              clinicalWorth: '' // 临床意义
            });
            break
          case 2:
            this.loreListOther.push({
              type: 2,
              name: '',
              linkUrl: '', // 链接
            });
            break
        }
      },
      delTable (index, table) {
        table.splice(index, 1);
      },
      onSubmit () {
        // 详情图片

        console.log(this.detailImageUrlArr)
        this.$refs.formdRefs.validate((valid) => {
          if (valid) {
            let cloneData = this.formdata;
            cloneData.loreList = [...this.loreListOther, ...this.formdata.loreList];
            cloneData.way = 1;
            // return
            this.post(this.api.cooperationHospital.healthCheckManageuploadInfo, cloneData).then(res => {
              if (res.data.code === '200') {
                this.$message.success('保存成功!');
                this.$parent._getList();
                this.modalClose();
              }
            })
          }
        })
      },

      loreListSuccess (response, file, fileList, index) {
        this.formdata.loreList.forEach((ele, i) => {
          if (index == i) {
            this.$set(ele, 'imageUrl', response.object[0]);
          }
        })
      },
      handleAvatarSuccess (res) {
        this.formdata.imageUrl = res.object[0];
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      // 详情图片
      handlePictureCardPreview (res) {
        if (res.code === '200') {
          this.detailImageUrlArr.push(res.object[0]);
          this.$message.success('上传成功!');
          this.formdata.detailImageUrl = JSON.stringify(this.detailImageUrlArr);
        }
      },
      onremove (res, list) {
        if (res.response) {
          this.detailImageUrlArr = this.detailImageUrlArr.filter(ele => ele != res.response.object[0]);
        } else {
          this.detailImageUrlArr = this.detailImageUrlArr.filter(ele => ele != res.url);
        }
      },
      onexceed () {
        this.$message.warning('详情图片至多上传6张');
      }
    },
    created () {
      // 获取关联商品
      this.post(this.api.cooperationHospital.getAllGoodsItem).then(res => {
        if (res.data.code === '200') {
          this.getAllGoodsItem = res.data.object;
        }
      })
      if (this.dialogData.info) {
        this.post(this.api.cooperationHospital.healthCheckManagegetDetail, {
          id: this.dialogData.info.id
        }).then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            let cloneData = JSON.parse(JSON.stringify(resData));
            this.formdata = resData;
            this.detailImageUrlArr = JSON.parse(this.formdata.detailImageUrl);
            this.formdata.detailImage = [];
            this.detailImageUrlArr.forEach(ele => {
              this.formdata.detailImage.push({
                name: ele,
                url: ele,
              });
            })
            this.formdata.loreList = cloneData.loreList.filter(ele => ele.type == 1);
            this.loreListOther = cloneData.loreList.filter(ele => ele.type == 2);
          }
        })
      }
    }
  }
</script>

<style >
  .el-upload-list--picture-card .el-upload-list__item {
    width: 98px !important;
    height: 98px !important;
  }
  .el-upload--picture-card {
    width: 98px !important;
    height: 98px !important;
    line-height: 98px !important;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 98px !important;
    height: 98px !important;
    line-height: 98px !important;
    text-align: center;
  }
  .avatar {
    width: 98px !important;
    height: 98px !important;
    display: block;
  }
</style>